package org.example.newcoder_summer.filter;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.newcoder_summer.pojo.Result;
import org.example.newcoder_summer.utils.JwtUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res =  (HttpServletResponse) servletResponse;

        //判断请求路径中是否包含Login，包含则说明为登陆操作，放行
        String url = req.getRequestURI();
        String[] urls = {"/element-ui", "/js", "/login.html", "/user_home.html",
                "/register.html", "/register", "/login"};

        log.info("url:{}", url);
        for (String s : urls) {
            if (url.contains(s)) {
                filterChain.doFilter(req, res);
                return;
            }
        }

        //判断请求头中是否包含令牌
        String token = req.getHeader("token");
        if(token == null){
            log.info("token为空，不放行");
            Result error = Result.error("未登录");
            String notLogin = JSONObject.toJSONString(error);
            res.getWriter().write(notLogin);
            return;
        }

        //解析令牌
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌解析失败");
            Result error = Result.error("未登录");
            String notLogin = JSONObject.toJSONString(error);
            res.getWriter().write(notLogin);
            return;
        }

        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
